import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SelectKeyGenerator;

public class XMLStatementBuilder extends BaseBuilder {
    // ... existing code ...
    
    public void parseStatementNode() {
        // ... existing statement parsing code ...
        
        // 解析 selectKey 节点
        parseSelectKeyNodes(id, parameterTypeClass, langDriver);
        
        // ... rest of existing code ...
    }
    
    private void parseSelectKeyNodes(String baseId, Class<?> parameterTypeClass, LanguageDriver langDriver) {
        List<XNode> selectKeyNodes = context.evalNodes("selectKey");
        if (selectKeyNodes != null && !selectKeyNodes.isEmpty()) {
            for (XNode keyNode : selectKeyNodes) {
                String keyId = baseId + SelectKeyGenerator.SELECT_KEY_SUFFIX;
                parseSelectKeyNode(keyId, keyNode, parameterTypeClass, langDriver);
            }
        }
    }
    
    private void parseSelectKeyNode(String id, XNode keyNode, Class<?> parameterTypeClass, LanguageDriver langDriver) {
        String resultType = keyNode.getStringAttribute("resultType");
        Class<?> resultTypeClass = resolveClass(resultType);
        String keyProperty = keyNode.getStringAttribute("keyProperty");
        String keyColumn = keyNode.getStringAttribute("keyColumn");
        boolean executeBefore = "BEFORE".equals(keyNode.getStringAttribute("order", "AFTER"));
        
        // 默认为 MYSQL
        String databaseId = configuration.getDatabaseId();
        
        // 创建 MappedStatement
        MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, langDriver.createSqlSource(configuration, keyNode, parameterTypeClass), SqlCommandType.SELECT);
        statementBuilder.resource(resource);
        statementBuilder.fetchSize(null);
        statementBuilder.statementType(StatementType.PREPARED);
        statementBuilder.keyGenerator(NoKeyGenerator.INSTANCE);
        statementBuilder.keyProperty(keyProperty);
        statementBuilder.keyColumn(keyColumn);
        statementBuilder.databaseId(databaseId);
        statementBuilder.resultOrdered(false);
        
        setStatementTimeout(statementBuilder);
        setStatementParameterMap(statementBuilder);
        setStatementResultMap(statementBuilder, resultTypeClass, id);
        
        configuration.addMappedStatement(statementBuilder.build());
        
        // 创建并注册 SelectKeyGenerator
        configuration.addKeyGenerator(id, new SelectKeyGenerator(statementBuilder.build(), executeBefore));
    }
} 